﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;

public partial class CreateAssignment : System.Web.UI.Page
{
    DataTable dt;
    public  string filePath;

    protected void Page_Load(object sender, EventArgs e)
    {
        //assId = Request.QueryString["AssignmentId"];
        //copyAssId = Request.QueryString["CopyAssignmentId"];
        if (!IsPostBack)
        {
            UserSelection.sObj.Clear();
            LoadSubject();
            if ((Request.QueryString["AssignmentId"] != null) && (Request.QueryString["AssignmentId"] != ""))
                setControlValues();
            if ((Request.QueryString["CopyAssignmentId"] != null) && (Request.QueryString["CopyAssignmentId"] != ""))
                setCopyControlValues();
            Session["FilePath"] = "";
        }
        filePath = Session["FilePath"].ToString();
        
    }

    

    private void setCopyControlValues()
    {
        DataSet ds = new DataSet();
        ds = AdminCreateTestDAL.GetAssignInfoByAssignId(Convert.ToInt32(Request.QueryString["CopyAssignmentId"]));
        txtAssigName.Text = "Copy of "+ds.Tables[0].Rows[0][1].ToString();
        ddlSub.Items.Clear();
        LoadSubject();
        ddlSub.SelectedIndex = -1;
        ddlSub.Items.FindByValue(ds.Tables[0].Rows[0][2].ToString()).Selected = true;

        dt = new DataTable();
        dt = AdminCreateTestDAL.getTopicRelatedToSubject(Convert.ToInt32(ddlSub.SelectedItem.Value));

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem li = new ListItem();
            li.Text = dt.Rows[i][0].ToString();
            li.Value = dt.Rows[i][1].ToString();
            ddlTopic.Items.Add(li);
        }
        ddlTopic.Items.FindByValue(ds.Tables[0].Rows[0][3].ToString()).Selected = true;
        txtQuestion.Text = ds.Tables[0].Rows[0][4].ToString();
        txtStartDate.Text = ds.Tables[0].Rows[0][6].ToString();
        txtEndDate.Text = ds.Tables[0].Rows[0][7].ToString();
        loadStatus();
        ddlStatus.Items.FindByText(ds.Tables[0].Rows[0][8].ToString()).Selected = true;
        if (Convert.ToInt32(ds.Tables[0].Rows[0][9]) == 1)
            chkNotify.Checked = true;
        else
            chkNotify.Checked = false;

        StudentInfo[] s = new StudentInfo[ds.Tables[1].Rows.Count];
        UserSelection.sObj.Clear();
        for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
        {
            s[j] = new StudentInfo();
            s[j].sid = Convert.ToInt32(ds.Tables[1].Rows[j][1]);
            s[j].sname = ds.Tables[1].Rows[j][2].ToString();
            UserSelection.sObj.Add(s[j]);
        } 
    }

    private void loadStatus()
    {
        ddlStatus.Items.Add("Scheduled");
        ddlStatus.Items.Add("Parked");
        ddlStatus.Items.Add("InProgress");
        ddlStatus.Items.Add("Completed");
        ddlStatus.Items.Add("Pending");
    }

    private void setControlValues()
    {
        DataSet ds = new DataSet();
        ds = AdminCreateTestDAL.GetAssignInfoByAssignId(Convert.ToInt32(Request.QueryString["AssignmentId"]));
        txtAssigName.Text = ds.Tables[0].Rows[0][1].ToString();
        ddlSub.Items.Clear();
        LoadSubject();
        ddlSub.SelectedIndex = -1;
        ddlSub.Items.FindByValue(ds.Tables[0].Rows[0][2].ToString()).Selected = true;

        dt = new DataTable();
        dt = AdminCreateTestDAL.getTopicRelatedToSubject(Convert.ToInt32(ddlSub.SelectedItem.Value));

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem li = new ListItem();
            li.Text = dt.Rows[i][0].ToString();
            li.Value = dt.Rows[i][1].ToString();
            ddlTopic.Items.Add(li);
        }
        ddlTopic.Items.FindByValue(ds.Tables[0].Rows[0][3].ToString()).Selected = true;
        txtQuestion.Text = ds.Tables[0].Rows[0][4].ToString();
        txtStartDate.Text = ds.Tables[0].Rows[0][6].ToString();
        txtEndDate.Text = ds.Tables[0].Rows[0][7].ToString();
        loadStatus();
        ddlStatus.Items.FindByText(ds.Tables[0].Rows[0][8].ToString()).Selected = true;
        if (Convert.ToInt32(ds.Tables[0].Rows[0][9]) == 1)
            chkNotify.Checked = true;
        else
            chkNotify.Checked = false;

        StudentInfo[] s = new StudentInfo[ds.Tables[1].Rows.Count];
        UserSelection.sObj.Clear();
        for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
        {
            s[j] = new StudentInfo();
            s[j].sid = Convert.ToInt32(ds.Tables[1].Rows[j][1]);
            s[j].sname = ds.Tables[1].Rows[j][2].ToString();
            UserSelection.sObj.Add(s[j]);
        }
    }

    private void LoadAllSub()
    {
        dt = new DataTable();
        dt = AdminCreateTestDAL.GetSubjects();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem li = new ListItem();
            li.Text = dt.Rows[i][0].ToString();
            li.Value = dt.Rows[i][1].ToString();
            ddlSub.Items.Add(li);
        }
    }

    private void LoadSubject()
    {
        dt = new DataTable();
        dt = AdminCreateTestDAL.GetSubjects();
        ddlSub.Items.Add("--Select One--");
        ddlSub.SelectedIndex = ddlSub.Items.IndexOf(ddlSub.Items.FindByText("--Select One--"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem li = new ListItem();
            li.Text = dt.Rows[i][0].ToString();
            li.Value = dt.Rows[i][1].ToString();
            ddlSub.Items.Add(li);
        }
    }

    private void ClearAll()
    {
        txtAssigName.Text = "";
        txtStartDate.Text = "";
        txtEndDate.Text = "";
        txtQuestion.Text = "";
        chkNotify.Checked = false;
        ddlSub.SelectedIndex = -1;
        ddlTopic.Items.Clear();
        ddlStatus.SelectedIndex = 0;
        lablError.Text = "";
        lablAssNameError.Text = "";
        lablFile.Text = "";
        Session["FilePath"]="";
        filePath = "";
    }

    protected void ddlSub_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlTopic.Items.Clear();
        if (ddlSub.SelectedItem.Text == "--Select One--")
        {
            lablError.Text = "Please select one subject";

        }
        else
        {
            dt = new DataTable();
            dt = AdminCreateTestDAL.getTopicRelatedToSubject(Convert.ToInt32(ddlSub.SelectedItem.Value));
            ddlTopic.DataTextField = "TopicName";
            ddlTopic.DataValueField = "TopicId";
            ddlTopic.DataSource = dt;
            ddlTopic.DataBind();
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    ListItem li = new ListItem();
            //    li.Text = dt.Rows[i][0].ToString();
            //    li.Value = dt.Rows[i][1].ToString();
            //    ddlTopic.Items.Add(li);
            //}
        }
    }


    protected void CalendarDisplay_SelectionChanged(object sender, EventArgs e)
    {


        txtStartDate.Text = CalendarDisplay.SelectedDate.ToShortDateString();
        // CalendarDisplay.Visible = false;

    }
    protected void CalendarEndDt_SelectionChanged(object sender, EventArgs e)
    {
        txtEndDate.Text = cldDisplay.SelectedDate.ToShortDateString();
    }



    protected void btnClear_Click(object sender, EventArgs e)
    {
        ClearAll();
    }

    private void GetFile()
    {
        if (fileAttahUpload.HasFile)
        {
            string file = fileAttahUpload.PostedFile.FileName;
            string path = "~/Assignment/";
            fileAttahUpload.SaveAs(Server.MapPath(path) + file);
            Session["FilePath"] = "~/Assignment/" + file;
            filePath = Session["FilePath"].ToString();
        }

    }

    public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                              "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                              "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                              "2");

            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                 pGmailPassword);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                 "true");
            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;


            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //GetFile();
       
        string userId = "";
        int notiofication,sendCumulative;
        if (chkNotify.Checked == true)
            notiofication = 1;
        else
            notiofication = 0;

        if (chkSendCumulativereport.Checked == true)
            sendCumulative = 1;
        else
            sendCumulative = 0;
        for (int i = 0; i < UserSelection.sObj.Count; i++)
        {
            userId += UserSelection.sObj[i].sid.ToString() + "|";
        }
        if ((Request.QueryString["AssignmentId"] == null) || (Request.QueryString["AssignmentId"] == ""))
        {
            DataTable dtAssInfo = new DataTable();
            dtAssInfo = AdminCreateTestDAL.SetAssignment(txtAssigName.Text, Convert.ToInt32(ddlSub.SelectedValue), Convert.ToInt32(ddlTopic.SelectedValue), txtQuestion.Text, filePath, DateTime.Parse(txtStartDate.Text), DateTime.Parse(txtEndDate.Text), userId, ddlStatus.SelectedItem.Text, notiofication,sendCumulative);

            if (chkNotify.Checked == true)
            {
                lablError.Text = "Assignment Created Successfully. Please Wait We are Sending Mails to Assignment Schedulers";
                DataTable dtEmailInfo = new DataTable();
                dtEmailInfo = AdminCreateTestDAL.GetAssignmentInfoForMail(Convert.ToInt32(dtAssInfo.Rows[0][0]));

                StringBuilder sbMail = new StringBuilder();
                sbMail.Append("<table width='70%'><tr><td>AssignmentId:<b> " + dtEmailInfo.Rows[0][0].ToString() + "</b></td></tr>");
                sbMail.Append("<tr><td>Assignment Name:<b> " + dtEmailInfo.Rows[0][1].ToString() + "</b></td></tr><tr><td></td></tr>");
                sbMail.Append("<tr><td>Subject Name:<b> " + dtEmailInfo.Rows[0][2].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>Topics:<b> " + dtEmailInfo.Rows[0][3].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>Expiry Date:<b> " + dtEmailInfo.Rows[0][4].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td><a href='http://www.skillify.net//Student/MyAssignments.aspx'>Click here to go to assignment</a>" + "</td></tr></table>");

                ClearAll();
                

                string use = userId;
                string[] users = use.Split('|');
                for (int k = 0; k < users.Length - 1; k++)
                {
                    DataTable dtEmail = new DataTable();
                    dtEmail = AdminCreateTestDAL.GetUserEmail(users[k]);
                    ConfigurationManager.AppSettings["ContactEmailTo"] = dtEmail.Rows[0][0].ToString();
                    if (SendEmail(ConfigurationManager.AppSettings["ContactEmailFrom"], ConfigurationManager.AppSettings["ContactEmailPassword"], ConfigurationManager.AppSettings["ContactEmailTo"], "Skillify.net - Assignment \"" + dtEmailInfo.Rows[0][1].ToString() + "\" is assigned to you", sbMail.ToString(), System.Web.Mail.MailFormat.Html, "") == true)
                    {

                    }
                }
                lablError.Text = "Mail Send to all Assignment Schedulers Successfully.";
            }
            else
            {
                lablError.Text = "Assignment Created Successfully";
            }
        }
        else
        {
            AdminCreateTestDAL.SetAssignmentUpdate(Convert.ToInt32(Request.QueryString["AssignmentId"]), txtAssigName.Text, Convert.ToInt32(ddlSub.SelectedValue), Convert.ToInt32(ddlTopic.SelectedValue), txtQuestion.Text, filePath, DateTime.Parse(txtStartDate.Text), DateTime.Parse(txtEndDate.Text), userId, ddlStatus.SelectedItem.Text, notiofication,sendCumulative);
            ClearAll();
            lablError.Text = "Assignment Updated Successfully";
        }
        
        
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            GetFile();
            lablFile.Text = "File " + fileAttahUpload.PostedFile.FileName + " is uploaded successfully.";
        }
        catch
        {
            lablFile.Text = "Error while uploading file";
        }
    }
    protected void txtAssigName_TextChanged(object sender, EventArgs e)
    {
        lablAssNameError.Text = "";
        dt = new DataTable();
        dt = AdminCreateTestDAL.getAssignmentNames();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (txtAssigName.Text.ToLower() == dt.Rows[i][0].ToString().ToLower())
            {
                lablAssNameError.Text = "Please Enter Diffrent Assignment Name";
                txtAssigName.Text = "";
                txtAssigName.Focus();
                break;
            }
        }
    }
}